
package org.yunai.swjg.server.module.scene.core.msg;

import org.slf4j.Logger;
import org.yunai.swjg.server.core.annotation.MainThread;
import org.yunai.swjg.server.core.service.GamingState;
import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.core.service.OnlineContextService;
import org.yunai.swjg.server.core.service.OnlineState;
import org.yunai.swjg.server.module.player.PlayerExitReason;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.message.sys.SysInternalMessage;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 玩家进入场景结果<br />
 * 系统内部调用消息
 * User: yunai
 * Date: 13-4-24
 * Time: 上午10:56
 */
public class SysPlayerEnterSceneResult extends SysInternalMessage {

    public static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.scene, SysPlayerEnterSceneResult.class);

    private static OnlineContextService onlineContextService;
    static {
        onlineContextService = BeanManager.getBean(OnlineContextService.class);
    }

    /**
     * 玩家编号
     */
    private Integer playerId;
    /**
     * 进入场景结果
     */
    private boolean success;

    public SysPlayerEnterSceneResult(Integer playerId, boolean success) {
        this.playerId = playerId;
        this.success = success;
    }

    /**
     * 若进入场景成功，则设置其在线状态和游戏状态<br />
     * 若进入场景失败，则将玩家断开连接
     */
    @Override
    @MainThread
    public void execute() {
        // 防止用户已经下线或者正在下线
        Online online = onlineContextService.getPlayer(playerId);
        if (online == null || online.getState() == OnlineState.logouting) {
            return;
        }
        // 进入场景失败，将该玩家下线
        if (!success) {
            LOGGER.error("[execute] [enter scene failure, player:{} will be kicked!].", playerId);
            online.setExitReason(PlayerExitReason.SERVER_ERROR);
            online.disconnect();
            return;
        }
        // 设置在线状态
        if (online.getState() == OnlineState.enter_sceneing) { // 第一次进入场景时候时候，将状态设置为OnlineState.gaming
            online.setState(OnlineState.gaming);
        } else if (online.getState() == OnlineState.gaming) {
            if (online.getGamingState() == GamingState.SWITCH_NORMAL_SCENE) {
                online.setGamingState(GamingState.NULL);
            } else if (online.getGamingState() == GamingState.SWITCH_REP_SCENE) {
                online.setGamingState(GamingState.IN_REP_SCENE);
            }
        }
    }

    @Override
    public short getCode() {
        return 0;
    }
}
